// frontend/src/admin/Statistics.js

import React, { useState, useEffect, useCallback } from "react";
import { Button, DatePicker, Form, Input, Select, Table, message } from "antd";
import { adminAPI } from "../services/api";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";
import moment from "moment"; // 确保 moment 被引入

const { RangePicker } = DatePicker;
const { Option } = Select;

const Statistics = () => {
  const [roomStats, setRoomStats] = useState([]);
  const [consumptionStats, setConsumptionStats] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  const fetchRoomStats = useCallback(async (params = {}) => {
    setLoading(true);
    try {
      // 确保路径是 /admin/stats/rooms
      const response = await adminAPI.getRoomStats(params);
      setRoomStats(response.data || []); // 确保返回的是数组
      message.success("房间统计数据加载成功");
    } catch (error) {
      message.error(
        "获取房间统计失败: " + (error.response?.data?.message || error.message)
      );
      console.error("Error fetching room statistics:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchConsumptionStats = useCallback(async (params = {}) => {
    setLoading(true);
    try {
      // 确保路径是 /admin/stats/consumptions
      const response = await adminAPI.getConsumptionStats(params);
      setConsumptionStats(response.data || []); // 确保返回的是数组
      console.log("API响应", response.config.url, response.data);
      message.success("消费统计数据加载成功");
    } catch (error) {
      message.error(
        "获取消费统计失败: " + (error.response?.data?.message || error.message)
      );
      console.error("Error fetching consumption statistics:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    // 初始加载时获取所有数据
    fetchRoomStats();
    fetchConsumptionStats();
  }, [fetchRoomStats, fetchConsumptionStats]);

  const onSearch = (values) => {
    const startDate = values.dateRange
      ? values.dateRange[0]?.format("YYYY-MM-DD")
      : undefined;
    const endDate = values.dateRange
      ? values.dateRange[1]?.format("YYYY-MM-DD")
      : undefined;

    fetchRoomStats({ startDate, endDate, room_type: values.room_type });
    fetchConsumptionStats({ startDate, endDate, item_name: values.item_name });
  };

  const columnsRoom = [
    { title: "房间类型", dataIndex: "room_type", key: "room_type" },
    { title: "入住次数", dataIndex: "total_checkins", key: "total_checkins" },
    {
      title: "总收入 (¥)",
      dataIndex: "total_revenue",
      key: "total_revenue",
      render: (text) => `¥${parseFloat(text).toFixed(2)}`,
    },
    {
      title: "平均入住天数",
      dataIndex: "avg_stay_days",
      key: "avg_stay_days",
      render: (text) => parseFloat(text).toFixed(1),
    },
  ];

  const columnsConsumption = [
    { title: "商品名称", dataIndex: "item_name", key: "item_name" },
    { title: "总数量", dataIndex: "total_quantity", key: "total_quantity" },
    {
      title: "总金额 (¥)",
      dataIndex: "total_amount",
      key: "total_amount",
      render: (text) => `¥${parseFloat(text).toFixed(2)}`,
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <h2>统计分析</h2>

      <Form
        form={form}
        layout="inline"
        onFinish={onSearch}
        style={{ marginBottom: 24 }}
      >
        <Form.Item name="dateRange" label="选择日期范围">
          <RangePicker />
        </Form.Item>
        <Form.Item name="room_type" label="房间类型">
          <Select placeholder="选择房间类型" style={{ width: 120 }} allowClear>
            <Option value="标准间">标准间</Option>
            <Option value="大床房">大床房</Option>
            <Option value="套房">套房</Option>
            {/* 更多房间类型可以从后端动态获取 */}
          </Select>
        </Form.Item>
        <Form.Item name="item_name" label="商品名称">
          <Input placeholder="输入商品名称" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            刷新数据
          </Button>
        </Form.Item>
      </Form>

      <h3>房间入住统计</h3>
      <div style={{ height: 300, marginBottom: 24 }}>
        {roomStats.length > 0 ? (
          <ResponsiveContainer width="100%" height="100%">
            <BarChart
              data={roomStats}
              margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
            >
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="room_type" />
              <YAxis />
              <Tooltip
                formatter={(value, name, props) => {
                  if (name === "total_revenue")
                    return [`¥${parseFloat(value).toFixed(2)}`, "总收入"];
                  if (name === "total_checkins")
                    return [`${value}`, "入住次数"];
                  if (name === "avg_stay_days")
                    return [
                      `${parseFloat(value).toFixed(1)}天`,
                      "平均入住天数",
                    ];
                  return value;
                }}
              />
              <Legend />
              <Bar dataKey="total_checkins" name="入住次数" fill="#8884d8" />
              <Bar dataKey="total_revenue" name="总收入 (¥)" fill="#82ca9d" />
              <Bar
                dataKey="avg_stay_days"
                name="平均入住天数 (天)"
                fill="#ffc658"
              />{" "}
              {/* 添加平均入住天数柱子 */}
            </BarChart>
          </ResponsiveContainer>
        ) : (
          <div style={{ textAlign: "center", padding: "50px" }}>
            暂无房间入住统计数据
          </div>
        )}
      </div>

      <Table
        columns={columnsRoom}
        dataSource={roomStats}
        rowKey="room_type"
        loading={loading}
        pagination={false}
        locale={{ emptyText: "暂无房间入住统计数据" }}
      />

      <h3 style={{ marginTop: 40 }}>商品消费统计</h3>
      <div style={{ height: 300, marginBottom: 24 }}>
        {consumptionStats.length > 0 ? (
          <ResponsiveContainer width="100%" height="100%">
            <BarChart
              data={consumptionStats}
              margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
            >
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="item_name" />
              <YAxis />
              <Tooltip
                formatter={(value, name, props) => {
                  if (name === "total_amount")
                    return [`¥${parseFloat(value).toFixed(2)}`, "总金额"];
                  return value;
                }}
              />
              <Legend />
              <Bar dataKey="total_quantity" name="总数量" fill="#ffc658" />
              <Bar dataKey="total_amount" name="总金额 (¥)" fill="#ff7300" />
            </BarChart>
          </ResponsiveContainer>
        ) : (
          <div style={{ textAlign: "center", padding: "50px" }}>
            暂无商品消费统计数据
          </div>
        )}
      </div>

      <Table
        columns={columnsConsumption}
        dataSource={consumptionStats}
        rowKey="item_name"
        loading={loading}
        pagination={false}
        locale={{ emptyText: "暂无商品消费统计数据" }}
      />
    </div>
  );
};

export default Statistics;
